package controller

import (
	"errors"
	"ginfast/api/middleware"
	"ginfast/api/system/internal"
	"ginfast/api/system/model"
	"ginfast/api/system/service"
	"ginfast/pkg/ginx"
	"ginfast/pkg/orm"
	"strings"

	"github.com/gin-gonic/gin"
	"github.com/mojocn/base64Captcha"
	"github.com/mssola/user_agent"
)

var store = base64Captcha.DefaultMemStore

var (
	errLogin          = errors.New("account or pssword error")
	errCaptachaVerify = errors.New("captcha verify error")
	errAuth           = errors.New("authentication error")
)

type loginxeq struct {
	Username string `json:"username" binding:"required,max=30"`
	Password string `json:"password" binding:"required,min=5,max=128"`
	Code     string `json:"verifyCode" binding:"required,min=4,max=10"`
	Key      string `json:"verifyKey" binding:"required,min=5,max=30"`
}

func login(user *model.User, c *gin.Context) error {
	var lo loginxeq
	if err := c.ShouldBindJSON(&lo); err != nil {
		return errLogin
	}
	if !store.Verify(lo.Key, lo.Code, true) {
		return errCaptachaVerify
	}
	user.UserName = lo.Username
	err := orm.DbFirstWhere(user, user)
	if err != nil {
		if lo.Username == model.UserName {
			user.Password = lo.Password
			err = service.UserCreate(user)
		}
	}
	if err != nil {
		return errLogin
	}
	if *user.Status == 0 {
		return errAuth
	}
	verifyPassword := service.UserPassword(user, lo.Password)
	if strings.Compare(user.Password, verifyPassword) != 0 {
		return errLogin
	}
	return nil
}

// LoginHandler 登录
func LoginHandler(c *gin.Context) {
	user, token := model.User{}, ""
	err := login(&user, c)
	if err == nil {
		token, err = middleware.JWTToken.Create(&middleware.UserClaims{UserID: user.ID, RoleID: user.RoleID, UserName: user.UserName})
	}
	lg := &model.LoginLog{}
	if err == nil {
		menus, permissions := service.MenuRouter(user.RoleID)
		ginx.JSON(c).WriteData(gin.H{"token": token, "userInfo": user, "menuList": menus, "permissions": permissions})
		lg.Msg = "登录成功"
	} else {
		lg.Status = 1
		lg.Msg = err.Error()
		ginx.JSON(c).WriteError(err)
	}
	lg.Name = user.UserName
	lg.Ipaddr = c.ClientIP()
	lg.Location = internal.IPCity(lg.Ipaddr)
	ua := user_agent.New(c.GetHeader("User-Agent"))
	lg.Browser, _ = ua.Browser()
	lg.Os = ua.OS()
	orm.DbCreate(lg)
}

func ApiLoginHandler(c *gin.Context) {
	user, token := model.User{}, ""
	err := login(&user, c)
	if err == nil {
		// token, err = middleware.TokenCreate(&middleware.UserClaims{UserID: user.ID, RoleID: user.RoleID, UserName: user.UserName})
	}
	ginx.JSON(c).WriteData(gin.H{"token": token}, err)
}

// LogoutHandler 注册
func LogoutHandler(c *gin.Context) {
	// c.Redirect(http.StatusFound, pkg.Conf.Local.ServeRoot)
	c.Abort()
}

// CaptchaImageHandler 图形验证码
func CaptchaImageHandler(c *gin.Context) {
	driver := base64Captcha.DefaultDriverDigit
	capC := base64Captcha.NewCaptcha(driver, store)
	//以base64编码
	id, b64s, err := capC.Generate()
	ginx.JSON(c).WriteData(gin.H{"img": b64s, "key": id}, err)
}
